package br.com.cliente;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/clienteServlet")
public class ClienteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       

    public ClienteServlet() {
        super();
       
    }

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String nomef = request.getParameter("nome");
		String emailf = request.getParameter("email");
		String enderecof = request.getParameter("endereco");
		String nacimentof =request.getParameter("nacimento");
		Calendar nacimento =null;
		PrintWriter out = response.getWriter();

		try {
			
			Date dt = new SimpleDateFormat("dd/MM/yyyy").parse(nacimentof);
			nacimento = Calendar.getInstance();
			nacimento.setTime(dt);
			
			
		} catch (Exception e) {
			System.out.println("Erro :"+e.getMessage());
		}
		
		
		if(nomef ==null || nomef.isEmpty()){
			out.println("Por favor preencha o nome corretamente");
			request.getRequestDispatcher("index.jsp").forward(request , response);
		}else if(emailf.isEmpty() || emailf == null){
			out.println("Por favor preencha o email corretamente");
			request.getRequestDispatcher("index.jsp").forward(request , response);
		}
			else{
		
		Cliente c1 = new Cliente();
		c1.setNome(nomef);
		c1.setEmail(emailf);
		c1.setEndereco(enderecof);
		c1.setNacimento(nacimento);
		ControleCliente c2 = new ControleCliente();
		c2.salvar(c1);
		request.setAttribute("msg","Cadastrado com Sucesso!");
		request.getRequestDispatcher("index.jsp").forward(request , response);
	 }
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		service(request,response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		service(request,response);
	}

}
